import React, { Component } from 'react';
import {
  StyleSheet, View, TouchableNativeFeedback, Text, Alert,
  Dimensions, Image, DeviceEventEmitter,
} from 'react-native';
import { Textarea } from 'native-base';
import produce from 'immer';
import { UtilToast } from '../../../../utils/util-method';
import { FormTakephoto } from '../../../../components';
import Theme from '../../../../native-base-theme/variables/commonColor';
import Option from './acceptOptions';
import * as incidentServer from '../../../../services/incidentRequest';
import * as todoService from '../../../../services/todo';

const deviceWidth = Dimensions.get('window').width;
const optionsList = ['故障已排除', '故障未排除'];

class CheckAndAccept extends Component {
  constructor(props) {
    super(props);
    this.state = {
      itemCkIndex: null,
      description: '',
      images: [],
    };
  }

  addImage = (uri) => {
    this.setState({
      images: [uri],
    });
    // this.setState(produce(draft => {
    //   draft.images.push(uri);
    // }));
  }

  delImage = (index) => {
    this.setState(produce(draft => {
      draft.images.splice(index, 1);
    }));
  }

  _optionsItemClick = (description, itemCkIndex) => {
    this.setState({
      itemCkIndex,
      description,
    });
  }

  _showAlert = (code) => {
    const title = code === '09' ? '验收通过' : '验收不通过';
    Alert.alert(
      '提示',
      `是否${title}`,
      [
        {
          text: '否',
          style: 'cancel',
          onPress: () => {
          },
        },
        {
          text: '是',
          onPress: () => {
            this._toServer(code);
          },
        },
      ],
    );
  }

  _toServer = async (code) => {
    try {
      let query = {
        description: this.state.description,
        stepCode: code,
        failureId: this.props.id,
      };
      // 未填写验收意见
      if (!query.description) {
        UtilToast('请填写验收意见！', 'danger');
        return;
      }

      // 图片上传  并且选中了是故障未排除
      DeviceEventEmitter.emit('showLoading', true);
      let picUp;
      if (this.state.images && this.state.images.length) {
        picUp = await todoService.uploadPic(this.state.images);
      } else {
        picUp = { data: { fileId: '' } };
      }
      query.picture = picUp.data.fileId;
      query = Object.assign(query, this.props.mobileInfo);
      const resp = await incidentServer.incidentHandle(query);
      DeviceEventEmitter.emit('showLoading', false);
      this._handleServerResponse(resp);
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      console.log('图片上传：', error);
    }
  }

  _handleServerResponse = (resp) => {
    if (resp.resultCode == '0') { // 状态码成功
      UtilToast('操作成功', 'success');
      // Toast.show({
      //   type: 'success',
      //   text: '操作成功',
      //   duration: 1000,
      //   position: 'bottom',
      // });
    } else {
      UtilToast(resp.resultMsg || '操作失败，请重试', 'danger');
      // Toast.show({
      //   type: 'danger',
      //   text: resp.resultMsg || '操作失败，请重试',
      //   duration: 1000,
      //   position: 'bottom',
      // });
    }
    this.props.back();
  }

  showBigImage = () => {
    DeviceEventEmitter.emit('showBigImage', { show: true, url: this.state.images[0].uri });
  }

  render() {
    return (
      <View style={styles.conatiner}>
        <View>
          <Text style={[styles.textFont]}>验收意见</Text>
          <Textarea
            rowSpan={6}
            bordered
            style={[styles.textAreaStyle]}
            placeholder="请输入验收意见"
            value={this.state.description}
            onChangeText={description => this.setState({ description })}
          />
          <View style={styles.item}>
            <Option
              onClick={this._optionsItemClick}
              optionsList={optionsList}
              ckIndex={this.state.itemCkIndex}
            />
          </View>
          <View style={{ marginTop: 5 }}>
            <View style={{ paddingLeft: 20, paddingRight: 20 }}>
              <Text style={styles.textFont}>验收照片</Text>
            </View>
            <View style={{ paddingLeft: 20, paddingRight: 20 }}>
              <FormTakephoto
                datas={this.state.images}
                addImage={this.addImage}
                delImage={this.delImage}
                showBigImage={this.showBigImage}
              />
            </View>
          </View>
        </View>
        <View>
          <Image
            source={require('../../../../../assets/images/btn-cut-line-xxx.png')}
            style={{ width: deviceWidth, height: 2, alignItems: 'center' }}
            resizeMode="stretch"
            resizeMethod="auto"
          />
          <View style={styles.oneItem}>
            <TouchableNativeFeedback
              onPress={() => this._showAlert('08')}
            >
              <View
                style={[styles.leftContent, styles.back]}
              >
                <Text style={styles.submitBtn}>验收不通过</Text>
              </View>
            </TouchableNativeFeedback>
            <TouchableNativeFeedback
              onPress={() => this._showAlert('09')}
            >
              <View
                style={[styles.rightContent, styles.close]}
              >
                <Text style={styles.submitBtn}>验收通过</Text>
              </View>
            </TouchableNativeFeedback>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  conatiner: {
    backgroundColor: Theme.myPrimary,
    display: 'flex',
    flex: 1,
    color: '#ffffff',
    justifyContent: 'space-between',
  },
  textFont: {
    paddingLeft: 20,
    color: '#ffffff',
  },
  item: {
    display: 'flex',
    flexDirection: 'row',
    paddingTop: 5,
    paddingBottom: 5,
  },
  oneItem: {
    display: 'flex',
    flexDirection: 'row',
  },
  leftContent: {
    flex: 0.5,
  },
  rightContent: {
    flex: 0.5,
  },
  textAreaStyle: {
    borderColor: '#ffffff',
    backgroundColor: '#ffffff',
    marginLeft: 20,
    marginRight: 20,
    borderRadius: 8,
  },
  submitBtn: {
    textAlign: 'center',
    color: '#ffffff',
    paddingTop: 15,
    paddingBottom: 15,
  },
  back: {
    backgroundColor: Theme.myPrimary,
  },
  close: {
    backgroundColor: Theme.myPrimary,
  },
});

export default CheckAndAccept;
